package com.le.springbootmybatis.controller;

import com.le.springbootmybatis.core.AjaxResult;
import com.le.springbootmybatis.model.User;
import com.le.springbootmybatis.service.UserService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
@AllArgsConstructor
@RequestMapping("user")
public class UserController {
    private UserService userService;

    @RequestMapping("/index")
    //@ResponseBody
    public String con() {
        System.out.println("hello");
        return "index";
    }

    @RequestMapping("userlist")
    public String list(Model model) {
        List<User> userList = userService.list();
        model.addAttribute("list", userList);
        return "user/userlist";
    }

    @GetMapping("add")
    public String add() {
        return "user/member-add";
    }

    @PostMapping("add")
    @ResponseBody
    public AjaxResult<String> add(User user) {
        userService.add(user);
        return new AjaxResult<String>("添加成功");
    }

    //    POST   http://localhost:8080/user/add
//    DELETE http://localhost:8080/user/delete
    @DeleteMapping("/delete/{id}")
    @ResponseBody
    public AjaxResult<String> delete(@PathVariable Integer id) {
        userService.delete(id);
        return new AjaxResult<String>("删除成功");
    }

    @RequestMapping("/edit/{id}")
    public String edit(@PathVariable Integer id, Model model) {
        User user = userService.selectById(id);
        model.addAttribute("user", user);
        return "user/member-edit";
    }

    @PostMapping("edit")
    @ResponseBody
    public AjaxResult<String> edit1(User user) {
        userService.edit(user);
        return new AjaxResult<String>("修改成功");
    }
}
